var pathUri = window.location.href;
$(function () {
    layui.use(['element', 'layer'], function () {
        var element = layui.element;
        var layer = layui.layer;
        getLeftMenu(element);
        getHomeData();
    });
})

function getLeftMenu(element) {
    // 左侧导航区域（可配合layui已有的垂直导航）
    $.ajax({
        type: "POST",
        url: ctxPath + "/system/user/getUserPerms",
        async: false,
        success: function (data) {
            if (data != null) {
                getMenus(data);
                element.render('nav');
            } else {
                layer.alert("权限不足，请联系管理员", function () {
                    //退出
                    window.location.href = "/logout";
                });
            }
        }
    });
}

var getMenus = function (data) {
    //回显选中
    var ul = $("<ul lay-shrink=\'all\' class='layui-nav layui-nav-tree' lay-filter='test'></ul>");
    for (var i = 0; i < data.length; i++) {
        var node = data[i];
        if (node.resourcetype == 0) {
            if (node.pId == -1) {
                var li = $("<li class='layui-nav-item' flag='" + node.id + "'></li>");
                //父级无page
                var a = $("<a lay-direction=\"2\" href='javascript:;'><i class=\"" + node.icon + "\"></i><cite>" + node.name + "</cite></a>");
                li.append(a);
                //获取子节点
                var childArry = getParentArry(node.id, data);
                if (childArry.length > 0) {
                    a.append("<span class='layui-nav-more'></span>");
                    var dl = $("<dl class='layui-nav-child'></dl>");
                    for (var y in childArry) {
                        var dd = $("<dd><a lay-href='" + ctxPath + childArry[y].url + "'>" + childArry[y].name + "</a></dd>");
                        //判断选中状态
                        if (pathUri.indexOf(childArry[y].url) > 0) {
                            li.addClass("layui-nav-itemed");
                            dd.addClass("layui-this")
                        }
                        //TODO 由于layui菜单不是规范统一的，多级菜单需要手动更改样式实现；
                        dl.append(dd);
                    }
                    li.append(dl);
                }
                ul.append(li);
            }
        }
    }
    $(".layui-side-scroll").append(ul);
}
//根据菜单主键id获取下级菜单
//id：菜单主键id
//arry：菜单数组信息
function getParentArry(id, arry) {
    var newArry = new Array();
    for (var x in arry) {
        if (arry[x].pId == id)
            newArry.push(arry[x]);
    }
    return newArry;
}

//获取首页右上角用户姓名
function getHomeData() {
    $.ajax({
        type: "GET",
        url: ctxPath + "/system/user/loginName",
        cache: false, //或者设置true
        success: function (data) {
            if (data.code == "1") {
                $("#realname").append(data.obj)
            } else {
                layer.alert(data.message)
            }
        }
    });
}